<?php


namespace App\Http\Controllers\user;


use App\Engine\BaseController;
use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Models\Goods as GoodsModel;
use Illuminate\Support\Facades\Cache;
use function app\Utils\go;
use App\Models\User as UserModel;
use App\Models\GoodsOrder as GoodsOrderModel;

class Goods extends BaseController
{
    /**获取商品套餐
     * @return array
     */
    public function getGoods()
    {
        $res=GoodsModel::paginate($this->get["num"]);
        return go($res);
    }

    /**id获取商品套餐
     * @return array
     */
    public function getGoodsId()
    {
        $res=GoodsModel::where("id",$this->get["id"])->first();
        return go($res);
    }

    /**
     * 创建商品
     */
    public function create_order()
    {
        $res=Cache::lock("create_order")->get(function (){
            $goods=GoodsModel::where("id",$this->get["id"])->first();
            if ($goods["stock"]<1)
                throw new ApiException("库存不足");
            $user=UserModel::where("id",TokenService::getCurrentUid())->first();
            if ($user["coupon"]<$goods["coupon_price"]){
                throw new ApiException("余额不足");
            }

            $create=[
                "goods_id"=>$this->get["id"],
                "uid"=>TokenService::getCurrentUid(),
                "price"=>$goods["coupon_price"],
                "state"=>0
            ];
            $res=GoodsOrderModel::create($create);
            return $res;
        });
        return go($res);
    }

    /**获取订单
     * @return array
     */
    public function get_order()
    {
        $res=GoodsOrderModel::with(["user","goods"])
            ->where("uid",TokenService::getCurrentUid())
            ->where("state",$this->get["state"])->paginate($this->get["num"]);
        return go($res);
    }


    /**
     * 核销订单
     */
    public function hx_order()
    {
        $res=GoodsOrderModel::where("id",$this->get["id"])->first();
        if (!$res)
            throw new ApiException("订单不存在");
        if ($res["state"]==1)
            throw new ApiException("订单已核销过");
        $goods=GoodsModel::where("id",$res["goods_id"])->first();
        if (!$goods)
            throw new ApiException("商品不存在");
        if ($goods["code"]!=$this->get["code"])
            throw new ApiException("核销码不正确");
        $res=GoodsOrderModel::where("id",$this->get["id"])->update(["state"=>1]);
        return go($res);
    }

}
